package bitmap.demo.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class RedisUtils {
    @Autowired
    private JedisPool jedisPool;

    public String getBit(String key,Long offet){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.getbit(key,offet)==true?"1":"0";
        } catch (Exception e) {
            return "0";
        } finally {
            jedis.close();
        }
    }

    public Boolean isExist(String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.exists(key);
        } catch (Exception e) {
            return false;
        } finally {
            jedis.close();
        }
    }

    /**
     * 向Redis中存值，永久有效
     */
    public String set(String key, String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.set(key, value);
        } catch (Exception e) {
            return "0";
        } finally {
            jedis.close();
        }
    }

    public Boolean setBit(String key,long offset,String value){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.setbit(key,offset,value);
        } catch (Exception e) {
            return false;
        } finally {
            jedis.close();
        }

    }

    public Boolean setBit(String key,long offset,char value){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.setbit(key,offset,value=='1'?true:false);
        } catch (Exception e) {
            return false;
        } finally {
            jedis.close();
        }

    }
}

